//
//  StatusPictureView.swift
//  Sina
//
//  Created by 王杰 on 15/11/17.
//  Copyright © 2015年 王杰. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let PictureCellId = "PictureCellId"

private let PictureCellMargin: CGFloat = 5
class StatusPictureView: UICollectionView {
    
    var imageURLs:[NSURL]? {
        
        didSet{
            //刷新数据
            reloadData()
            print(imageURLs)//打印图片的地址测试
            let viewSize = self.calculateSize()
            
            self.snp_updateConstraints { (make) -> Void in
                
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
                
            }
            testLabel.text = "\(imageURLs?.count ?? 0)"
        }
        
    }
    //计算配图视图的大小
    private func calculateSize() ->CGSize {
        
        let colum: CGFloat = 3.00000000001
        
        let maxWidth = screenW - 2 * StatusCellMargin
        //单个图片的宽度
        let itemWidth = (maxWidth - 2 * PictureCellMargin) / colum
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        let imageCount = imageURLs?.count ?? 0
        
        if imageCount == 0 {

            return CGSizeZero
        }
        if imageCount == 1 {
            //获取单张被缓存的图片
            let key = imageURLs?.last?.absoluteString
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key!)
            let imageSize = image.size
            layout.itemSize = imageSize
            return imageSize
        }
        if imageCount == 4 {
            let w = itemWidth * 2 + PictureCellMargin
            
            return CGSize(width: w, height: w)
            
        }
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let h = itemWidth * row + (row - 1) * PictureCellMargin
        let w = maxWidth
        return CGSize(width: w, height:h)
        
    }
    
    //设置frame
    
    init(){
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.minimumLineSpacing = PictureCellMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        registerClass(pictureCell.self, forCellWithReuseIdentifier: PictureCellId);
        
        dataSource = self
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置UI
    private func setupUI() {
        
        backgroundColor = UIColor.randomColor()
        addSubview(testLabel)
        testLabel.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(self.snp_center)
        }
        
    }
    //懒加载控件
    
    private lazy var testLabel: UILabel = {
        
        let lab = UILabel()
        
        lab.font = UIFont.systemFontOfSize(18)
        lab.textColor = UIColor.redColor()
        lab.sizeToFit()
        return lab
        
    }()
}
extension StatusPictureView:UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return imageURLs?.count ?? 0
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as!pictureCell
        
        cell.url = imageURLs![indexPath.item]
        return cell
    }
    
}

class pictureCell: UICollectionViewCell {
    
    var url: NSURL? {
        didSet{
            imageView.sd_setImageWithURL(url, placeholderImage: nil)
        }
        
    }
    
    
    //设置frame
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI
    
    private func setupUI() {
        
        contentView.addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
            
        }
        
    }
    //懒加载控件
    private lazy var imageView: UIImageView = {
        let iv = UIImageView()
        //设置图片显示样式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        //收写代码 必须自己手动添加 剪裁
        iv.clipsToBounds = true
        return iv
    }()
}














